<template>
  <div class="login-no-test">
    <LayOutLogin form-title-name="验证码登录">
      <template v-slot:form>
        <Form ref="formValidate" :model="formValidate" :rules="ruleValidate">
          <FormItem prop="userAccount" class="form-item-user">
            <i-input
              type="text"
              style="width: 100%"
              placeholder="手机号/邮箱"
              v-model="formValidate.userAccount"
            >
            </i-input>
          </FormItem>
          <FormItem class="form-item-captcha" prop="password">
            <i-input
              type="text"
              style="width: 100%"
              placeholder="验证码"
              v-model="formValidate.password"
            >
              <template v-slot:suffix>
                <span v-if="isGetCaptcha" key="captchaYes" v-text="useCountdownTime"></span>
                <span v-text="captchaText" @click="privateGetCaptcha('formValidate')" v-else key="captchaNo"></span>
              </template>
            </i-input>
          </FormItem>
          <FormItem class="ivu-form-btn">
            <Button
              type="primary"
              :loading="loading"
              long
              style="background-color: #2878FF"
              @click="handleSubmit('formValidate')">登录
            </Button>
          </FormItem>
          <FormItem class="form-other-login">
            <span></span>
            <span @click="handleAccountLogin()">返回账号登录</span>
          </FormItem>
        </Form>
      </template>
    </LayOutLogin>
  </div>
</template>

<script>
import { goLogin } from '../../router'
import { sendPhoneVerificationCode, sendMailVerificationCode } from '../../api/modules/system/msgTemplate'
import message from '../../utils/message'
import { JSEncrypt } from 'jsencrypt'
import { loginPhone, getRsaPublicKey, loginEmail } from '../../api/modules/login/login'
import { isPhone, isEmail } from '../../utils/verification'
import { saveLoginInfo } from '../../api/modules/login/saveLoginInfo'
export default {
  name: 'LoginPhone',
  data () {
    // 自定义手机号、邮箱验证
    const validateAccount = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('手机号或邮箱不能为空'))
      } else if (isPhone(value)) {
        callback()
      } else if (isEmail(value)) {
        callback()
      } else {
        callback(new Error('手机号或邮箱格式错误'))
      }
    }
    return {
      formValidate: {
        userAccount: '',
        rsaKey: '',
        password: ''
      },
      publicKey: '',
      ruleValidate: {
        userAccount: [{ validator: validateAccount, trigger: 'blur' }],
        password: [{ required: true, message: '验证码不能为空', trigger: 'blur' },
          { min: 6, trigger: 'blur', message: '验证码为6位数' }]
      },
      loading: false,
      isGetCaptcha: false,
      captchaText: '获取验证码',
      timeId: null,
      countdownTime: 60,
      formCode: {
        account: '',
        rsaKey: '',
        verificationCode: ''
      },
      getCaptchaType: ''
    }
  },
  computed: {
    useCountdownTime () {
      return `重新发送(${this.countdownTime}) `
    }
  },
  methods: {
    /**
       * 登录
       * @param name
       */
    handleSubmit (name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          const userAccount = this.formValidate.userAccount
          if (isPhone(userAccount)) {
            this.$_updateSubmit(1)
          } else if (isEmail(userAccount)) {
            this.$_updateSubmit(2)
          } else {}
        } else {
          message.message.error('输入数据格式错误，请检查后重试')
        }
      })
    },
    /**
     * 登录请求处理
     */
    $_updateSubmit (type) {
      this.loading = true
      if (type === 1) {
        loginPhone(this.formValidate).then(data => {
          saveLoginInfo(data)
          this.loading = false
        }).catch(error => {
          if (error.code && error.code === '1030') {
            message.message.error((error.message || '系统错误') + ',3秒后为你跳转到绑定页', { duration: 3 }, () => {
              const userAccount = this.formValidate.userAccount
              this.$router.replace(`/loginBind/${userAccount}/${3}`)
            })
          } else {
            message.message.error(error.message || '系统异常')
          }
          this.loading = false
        })
      } else {
        loginEmail(this.formValidate).then(data => {
          saveLoginInfo(data)
        }).catch(error => {
          if (error.code && error.code === '1030') {
            message.message.error((error.message || '系统错误') + ',3秒后为你跳转到绑定页', { duration: 3 }, () => {
              const userAccount = this.formValidate.userAccount
              this.$router.replace(`/loginBind/${userAccount}/${2}`)
            })
          } else {
            message.message.error(error.message || '系统异常')
          }
          this.loading = false
        })
      }
    },
    /**
       * 返回账号登录
       */
    handleAccountLogin () {
      goLogin()
    },
    /**
       * 获取验证码
       */
    privateGetCaptcha (name) {
      this.$refs[name].validateField('userAccount', (error) => {
        if (error) {
          message.message.error('手机号或邮箱不能为空或格式错误')
        } else {
          const userAccount = this.formValidate.userAccount
          if (isPhone(userAccount)) {
            this.$_getVerification(1)
          } else if (isEmail(userAccount)) {
            this.$_getVerification(2)
          } else {}
        }
      })
    },
    /**
     * 验证码计时
     */
    cationCodeTime () {
      this.isGetCaptcha = true
      this.timeId = setInterval(() => {
        this.countdownTime -= 1
      }, 1000)
    },
    /**
     * 获取验证码
     */
    $_getVerification (type = 1) {
      // 开始倒计时
      this.cationCodeTime()
      // 获取公钥
      getRsaPublicKey().then(({ data }) => {
        const { rsaKey, publicKey } = data
        this.formValidate.rsaKey = rsaKey
        const account = this.formValidate.userAccount
        const enc = new JSEncrypt()
        enc.setPublicKey(publicKey)
        const verificationCode = enc.encrypt(account)
        const params = {
          account,
          rsaKey,
          verificationCode
        }
        return params
      }).then(data => {
        // type为1表示手机验证码，反之邮箱验证码
        if (type === 1) {
          return sendPhoneVerificationCode(data)
        } else {
          return sendMailVerificationCode(data)
        }
      }).then(data => {
        message.message.success(data.message)
      }).catch(error => {
        message.message.error(error.message || '系统错误')
        this.isGetCaptcha = false
      })
    }
  },
  components: {
    LayOutLogin: () => import('./LayOutLogin')
  },
  /**
     * 组件销毁前触发
     */
  beforeDestroy () {
    clearInterval(this.timeId)
  },
  watch: {
    countdownTime (val) {
      if (val === 0) {
        // 移除监听，重新赋值
        clearInterval(this.timeId)
        this.countdownTime = 60
        this.isGetCaptcha = false
      }
    }
  }
}
</script>

<style scoped lang="scss">
  @import "../../assets/styles/scss/mixin";
  .login-no-test{
    height: 100%;
  }
  /deep/ .ivu-input {
    border-radius: 0px;
    border: 1px solid rgba(230, 230, 230, 1);
    height: .5rem;
  }

  .ivu-form {
    margin-top: .7rem;
    /*margin-top: 6.48%;*/
  }

  .ivu-btn {
    border-radius: 0px;
    height: .5rem;
  }

  .ivu-form-item {
    margin-bottom: .4rem;
  }

  .form-item-other {
    /deep/ .ivu-form-item-content {
      line-height: 0;
      @include flexMixer(space-between);
      color: #B3B3B3;
    }
  }

  /deep/ .form-item-captcha {
    .ivu-input-suffix {
      width: auto;
      color: #396AFE;
      margin-right: .16rem;
      line-height: .5rem;
      cursor: pointer;
    }
  }

  .ivu-form-btn {
    margin-bottom: 0px;
  }

  /deep/ .form-other-login {
    margin-bottom: 0;
    height: .5rem;
    cursor: pointer;
    /deep/ .ivu-form-item-content {
      height: 100%;
      width: 100%;
      @include flexMixer(space-between);
      color: #B3B3B3;
    }
  }
</style>
